import React from 'react';
import { Select } from 'antd';
import { axhelper } from '@/shared/axhelper';

let storageKey;
/**
 * 自定义搜索下拉框
 * @param label 标签
 * @param field 字段名称
 * @param axvalue 默认值
 * @param data 选项数据 [{ value: '1', text: 'Demo' }]
 * @param allowClear 允许为空（默认：false）
 * @param mode 模式 'multiple' | 'tags' | '-'
 * @param placeholder 占位符
 */
export class AxSelectForSimple extends React.Component {
  constructor(props) {
    super(props);
    const value = props.axvalue;
    const { field, remember } = props;

    this.state = {
      value,
      axvalue: value,
    };

    if (remember === true) {
      storageKey = axhelper.getPageStorageKey(field);
    }
  }

  componentWillReceiveProps(newProps) {
    const { axvalue } = newProps;
    const { axvalue: preAxvalue } = this.state;

    // 这段代码可能看起来非常混乱，这个props可以被当做缓存，仅用作判断
    if (axvalue !== preAxvalue) {
      const { onChange, remember } = this.props;
      this.setState({
        value: axvalue,
        axvalue,
      });
      if (onChange) {
        onChange(axvalue);
      }
      if (remember === true) {
        localStorage.setItem(storageKey, axvalue);
      }
    }
  }

  handleChange = val => {
    const { onChange, remember } = this.props;
    this.setState({
      value: val,
    });
    if (onChange) {
      onChange(val);
    }
    if (remember === true) {
      localStorage.setItem(storageKey, val);
    }
  };

  render() {
    const { value } = this.state;
    const { placeholder, label, mode, data, allowClear = false, ...rest } = this.props;

    return (
      <Select
        maxTagCount={1}
        {...rest}
        size={window.ax.config.size}
        allowClear={allowClear}
        mode={mode ? mode : '-'}
        placeholder={placeholder ? placeholder : `请选择${label}`}
        value={value}
        onChange={this.handleChange}
        filterOption={(input, option) =>
          option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
        }
      >
        {data.map(d => (
          <Select.Option key={d.value} value={d.value}>
            {d.text}
          </Select.Option>
        ))}
      </Select>
    );
  }
}
